package com.ruoyi.stomp.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @ClassName WebSocketConfig
 * @Description TODO
 * @Author li yang
 * @Date 2025/9/3 17:42
 * @Version 1.0
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketStompConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 原生 WS 端点
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*");

        // SockJS 端点（回退兼容）
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 简单内存代理：广播 /topic，点对点 /queue
        registry.enableSimpleBroker("/topic", "/queue")
                .setHeartbeatValue(new long[]{0, 0});

        // 客户端发送到应用的前缀，对应 @MessageMapping
        registry.setApplicationDestinationPrefixes("/app");

        // 用户目的地前缀：/user/queue/xxx（客户端订阅时不写用户名）
        registry.setUserDestinationPrefix("/user");
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        // 可添加 ChannelInterceptor 进行鉴权/限流/审计
    }
}